#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from functools import lru_cache
from pathlib import Path
from typing import Optional

from glom import glom

from autoapi.common.errors import ConfigInitError
from autoapi.common.yaml_handler import YamlHandler

__all__ = ["autoapi_config"]


class autoapiConfig:
    def __init__(self) -> None:
        self.settings = YamlHandler.read_file(str(Path(__file__).resolve().parent), "conf.yaml")
        try:
            # 项目目录名
            self.PROJECT_NAME = glom(self.settings, "project.name")

            # 测试报告
            self.TEST_REPORT_TITLE = glom(self.settings, "report.title")
            self.TESTER_NAME = glom(self.settings, "report.tester_name")
            self.JENKINS_URL = glom(self.settings, "report.jenkins_url")

            # redis 数据库
            self.REDIS_HOST = glom(self.settings, "redis.host")
            self.REDIS_PORT = glom(self.settings, "redis.port")
            self.REDIS_PASSWORD = glom(self.settings, "redis.password")
            self.REDIS_DATABASE = glom(self.settings, "redis.database")
            self.REDIS_TIMEOUT = glom(self.settings, "redis.timeout")

            # 邮件
            self.EMAIL_SERVER = glom(self.settings, "email.host")
            self.EMAIL_PORT = glom(self.settings, "email.port")
            self.EMAIL_USER = glom(self.settings, "email.user")
            self.EMAIL_PASSWORD = glom(self.settings, "email.password")
            self.EMAIL_SEND_TO = glom(self.settings, "email.receiver")
            self.EMAIL_SSL = glom(self.settings, "email.ssl")
            self.EMAIL_SEND = glom(self.settings, "email.send")

            # 钉钉
            self.DINGDING_WEBHOOK = glom(self.settings, "dingding.webhook")
            self.DINGDING_PROXY = {
                "http": (
                    glom(self.settings, "dingding.proxies.http")
                    if glom(self.settings, "dingding.proxies.http") != ""
                    else None
                ),
                "https": (
                    glom(self.settings, "dingding.proxies.https")
                    if glom(self.settings, "dingding.proxies.https") != ""
                    else None
                ),
            }
            self.DINGDING_SEND = glom(self.settings, "dingding.send")

            # 飞书
            self.FEISHU_WEBHOOK = glom(self.settings, "feishu.webhook")
            self.FEISHU_PROXY = {
                "http": (
                    glom(self.settings, "feishu.proxies.http")
                    if glom(self.settings, "feishu.proxies.http") != ""
                    else None
                ),
                "https": (
                    glom(self.settings, "feishu.proxies.https")
                    if glom(self.settings, "feishu.proxies.https") != ""
                    else None
                ),
            }
            self.FEISHU_MENTION_USERS = glom(self.settings, "feishu.mention_user")
            self.FEISHU_SEND = glom(self.settings, "feishu.send")

            # 企业微信
            self.WECHAT_WEBHOOK = glom(self.settings, "wechat.webhook")
            self.WECHAT_PROXY = {
                "http": (
                    glom(self.settings, "wechat.proxies.http")
                    if glom(self.settings, "wechat.proxies.http") != ""
                    else None
                ),
                "https": (
                    glom(self.settings, "wechat.proxies.https")
                    if glom(self.settings, "wechat.proxies.https") != ""
                    else None
                ),
            }
            self.WECHAT_SEND = glom(self.settings, "wechat.send")

            # 请求发送
            self.REQUEST_GLOBAL_ENV = glom(self.settings, "request.global_env")
            self.REQUEST_TIMEOUT = glom(self.settings, "request.timeout")
            self.REQUEST_VERIFY = glom(self.settings, "request.verify")
            self.REQUEST_REDIRECTS = glom(self.settings, "request.redirects")
            self.REQUEST_PROXIES_REQUESTS = {
                "http": (
                    glom(self.settings, "request.proxies.http")
                    if glom(self.settings, "request.proxies.http") != ""
                    else None
                ),
                "https": (
                    glom(self.settings, "request.proxies.https")
                    if glom(self.settings, "request.proxies.https") != ""
                    else None
                ),
            }
            self.REQUEST_PROXIES_HTTPX = {
                "http://": (
                    glom(self.settings, "request.proxies.http")
                    if glom(self.settings, "request.proxies.http") != ""
                    else None
                ),
                "https://": (
                    glom(self.settings, "request.proxies.https")
                    if glom(self.settings, "request.proxies.https") != ""
                    else None
                ),
            }
            self.REQUEST_RETRY = glom(self.settings, "request.retry")
            
            # 环境配置
            self.ENV_DEFAULT = glom(self.settings, "env.current")
            self.ENV_CONFIGS = self._get_env_configs()
        except KeyError as e:
            raise ConfigInitError(
                f"配置解析失败：缺失参数 {str(e)}，请核对项目配置文件"
            )

    @property
    def MYSQL_CONFIGS(self) -> dict:
        """获取所有MySQL数据库配置"""
        mysql_config = self.settings.get("mysql", {})

        # 检查是否是多数据库配置格式
        is_multi_db = False
        for key, value in mysql_config.items():
            if isinstance(value, dict) and key not in [
                "host",
                "port",
                "user",
                "password",
                "database",
                "charset",
                "cursorclass",
            ]:
                is_multi_db = True
                break

        if not is_multi_db:
            # 单数据库配置，保持向后兼容
            return {
                "main_db": {
                    "host": self.MYSQL_HOST,
                    "port": self.MYSQL_PORT,
                    "user": self.MYSQL_USER,
                    "password": self.MYSQL_PASSWORD,
                    "database": self.MYSQL_DATABASE,
                    "charset": self.MYSQL_CHARSET,
                    "cursorclass": "pymysql.cursors.DictCursor",
                }
            }
        else:
            # 多数据库配置
            configs = {}
            for key, value in mysql_config.items():
                if isinstance(value, dict):
                    configs[key] = value
            return configs

    @property
    def MYSQL_ENABLE(self) -> bool:
        """获取数据库连接开关"""
        mysql_config = self.settings.get("mysql", {})
        return mysql_config.get("enable", True)  # 默认启用，保持向后兼容

    @property
    def MYSQL_DEFAULT(self) -> str:
        """获取默认数据库名称"""
        mysql_config = self.settings.get("mysql", {})
        return mysql_config.get("default", "main_db")

    # 保持向后兼容性 - 这些属性现在基于默认数据库配置
    @property
    def MYSQL_HOST(self):
        default_config = self.MYSQL_CONFIGS.get(self.MYSQL_DEFAULT, {})
        return default_config.get("host", "localhost")

    @property
    def MYSQL_PORT(self):
        default_config = self.MYSQL_CONFIGS.get(self.MYSQL_DEFAULT, {})
        return default_config.get("port", 3306)

    @property
    def MYSQL_USER(self):
        default_config = self.MYSQL_CONFIGS.get(self.MYSQL_DEFAULT, {})
        return default_config.get("user", "root")

    @property
    def MYSQL_PASSWORD(self):
        default_config = self.MYSQL_CONFIGS.get(self.MYSQL_DEFAULT, {})
        return default_config.get("password", "")

    @property
    def MYSQL_DATABASE(self):
        default_config = self.MYSQL_CONFIGS.get(self.MYSQL_DEFAULT, {})
        return default_config.get("database", "")

    @property
    def MYSQL_CHARSET(self):
        default_config = self.MYSQL_CONFIGS.get(self.MYSQL_DEFAULT, {})
        return default_config.get("charset", "utf8mb4")

    def _get_env_configs(self) -> dict:
        """获取所有环境配置"""
        env_config = self.settings.get("env", {})
        
        # 检查是否是多环境配置格式
        is_multi_env = False
        for key, value in env_config.items():
            if isinstance(value, dict) and key not in ["current"]:
                is_multi_env = True
                break

        if not is_multi_env:
            # 单环境配置，保持向后兼容
            return {
                "dev": {
                    "HOST": env_config.get("HOST", "")
                }
            }
        else:
            # 多环境配置
            configs = {}
            for key, value in env_config.items():
                if isinstance(value, dict):
                    configs[key] = value
            return configs

    def get_env_config(self, env_name: Optional[str] = None) -> dict:
        """获取指定环境的配置"""
        if env_name is None:
            env_name = self.ENV_DEFAULT
        
        env_config = self.ENV_CONFIGS.get(env_name, {})
        return env_config

    def get_env_value(self, env_name: Optional[str] = None, key: Optional[str] = None, default: str = "") -> str:
        """获取指定环境的特定配置值"""
        if env_name is None:
            env_name = self.ENV_DEFAULT
        
        env_config = self.get_env_config(env_name)
        return env_config.get(key, default) if key else default

    def get_current_env_info(self) -> dict:
        """获取当前环境信息"""
        current_env = self.ENV_DEFAULT
        env_config = self.get_env_config(current_env)
        
        return {
            "current_env": current_env,
            "config": env_config,
            "available_envs": list(self.ENV_CONFIGS.keys())
        }


@lru_cache(maxsize=None)
def cache_autoapi_config() -> autoapiConfig:
    return autoapiConfig()


autoapi_config = cache_autoapi_config()
